package com.wxsoft.business.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.wxsoft.business.common.controller.BaseController;
import com.wxsoft.business.model.easyui.DataGrid;
import com.wxsoft.business.model.easyui.PageHelper;
import com.wxsoft.business.model.easyui.TreeForCombo;
import com.wxsoft.business.sys.pojo.SysMenu;
import com.wxsoft.business.sys.pojo.SysUser;
import com.wxsoft.business.sys.service.ISysMenuService;
import com.wxsoft.frame.cache.MenuCache;
import com.wxsoft.util.JsonUtil;
import com.wxsoft.util.UserUtil;
import com.wxsoft.util.common.Const;

@Controller
@RequestMapping("/sysMenu")
public class SysMenuController extends BaseController {

	private Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private ISysMenuService service;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		return "sys/sysMenulist";
	}

	@ResponseBody
	@RequestMapping("/datagrid")
	public DataGrid list(HttpServletRequest request, PageHelper page,
			SysMenu sysMenu, HttpServletResponse response) throws IOException {

		DataGrid dg = new DataGrid();
		dg.setTotal(service.findCount(sysMenu));
		List<SysMenu> sysMenuList = service.findAll(page, sysMenu);
		dg.setRows(sysMenuList);
		// JsonUtil.toResponse(response, dg);
		return dg;
	}

	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public void add(HttpServletRequest request, HttpServletResponse response,
			SysMenu sysMenu) {
		try {
			// 菜單 變更后， 緩存至為空
			MenuCache.setMenuTreeForCombo(null);
			SysUser user = UserUtil.getUser(request);
			sysMenu.setHandle(user.getUser_id());
			sysMenu.setHandle_date(new Date());
			String r = service.add(sysMenu);
			this.writeReturn(request, response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request,response , false, e.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public void modify(HttpServletRequest request,
			HttpServletResponse response, SysMenu sysMenu) {
		try {
			// 菜單 變更后， 緩存至為空
			MenuCache.setMenuTreeForCombo(null);
			SysUser user = UserUtil.getUser(request);
			sysMenu.setHandle(user.getUser_id());
			sysMenu.setHandle_date(new Date());
			String r = service.modify(sysMenu);
			this.writeReturn(request, response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request, response, e.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request,
			HttpServletResponse response, SysMenu sysMenu) {
		try {
			// 菜單 變更后， 緩存至為空
			MenuCache.setMenuTreeForCombo(null);
			String r = service.delete(sysMenu);
			this.writeReturn(request, response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request, response, e.getMessage());
		}
	}

	/**
	 * 获取所有菜单树
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/getMenuBy")
	public void getMenuBy(HttpSession session, HttpServletResponse response,
			SysMenu sysMenu) {
		String menuTreeStr = MenuCache.getMenuTreeForCombo();
		if (null == menuTreeStr || "".equals(menuTreeStr)) {
			SysUser user = (SysUser) session.getAttribute(Const.SESSION_USER);
			sysMenu.setStatus("qy");
			List<SysMenu> menuList = service.getMenuBy(sysMenu);
			List<TreeForCombo> treeList = getTree(menuList);
			String json = JSONArray.toJSONString(treeList);
			System.out.println(json);
			MenuCache.setMenuTreeForCombo(json);
			menuTreeStr = json;
		}
		JsonUtil.toResponse(response, menuTreeStr);
		// return menuTreeStr;
	}

    @ResponseBody
	@RequestMapping(value = "/getMenuByRole")
	public List<TreeForCombo> getMenuByRole(HttpSession session,
			HttpServletResponse response, String role_code) {
		
//		SysUser user = (SysUser) session.getAttribute(Const.SESSION_USER);
		List<SysMenu> menuList = service.getMenuByRole(role_code);
		List<TreeForCombo> treeList = getTree(menuList);
		
		return treeList ;
//		String json = JSONArray.toJSONString(treeList);
//		System.out.println(json);
//		
//		JsonUtil.toResponse(response, json);
		// return menuTreeStr;
	}

	/**
	 * 将菜单变成树形结构
	 * 
	 * @param menuList
	 * @return
	 */
	public List<TreeForCombo> getTree(List<SysMenu> menuList) {
		List<TreeForCombo> treeFList = new ArrayList<TreeForCombo>();

		TreeForCombo nodeF = new TreeForCombo();
		nodeF.setId("0");
		nodeF.setText("顶级菜单");
		nodeF.setPid("");
		addNode(nodeF, menuList);

		treeFList.add(nodeF);
		return treeFList;
	}

	public void addNode(TreeForCombo pNode, List<SysMenu> menuList) {
		List<TreeForCombo> treeList = new ArrayList<TreeForCombo>();

		for (SysMenu menu : menuList) {
			// 如果子节点父ID=父节点ID
			if (pNode.getId().equals(menu.getPcode())) {

				TreeForCombo node = new TreeForCombo();

				node.setId(menu.getCode());
				node.setPid(menu.getPcode());
				node.setText(menu.getName());
				treeList.add(node);
				addNode(node, menuList);
			}

		}
		pNode.setChildren(treeList);
	}

}
